package com.qianshui.co.medical.server;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.qianshui.co.medical.business.user.UserOperator;
import com.qianshui.co.medical.common.BuildResult;
import com.qianshui.co.medical.common.CommonJson;
import com.qianshui.co.medical.common.DateFormater;
import com.qianshui.co.medical.common.IDOperation;
import com.qianshui.co.medical.db.DaoFactory;
import com.qianshui.co.medical.db.NormalAnswer;
import com.qianshui.co.medical.db.PrivateAnswer;
import com.qianshui.co.medical.db.PrivateAnswerView;
import com.qianshui.co.medical.db.PrivateQuestionView;
import com.qianshui.co.medical.db.PublicQuestionView;
import com.qianshui.co.medical.db.Question;
import com.qianshui.co.medical.db.Score;

@Path("AdvisoryUtilService")
public class AdvisoryUtilService {
	
	//查询所有公开的提问
	@GET
	@Path("queryAllPublicAdvisoryQuestion")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryAllPublicAdvisoryQuestion()
			throws UnsupportedEncodingException {
		try {
			String sql="select * from question where private="+0+" ORDER BY createdate DESC";
			List<Question> question=DaoFactory.getInstance().getQuestion_dao().query(sql);
			
            if (question != null && question.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, question);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//分页查询
	@GET
	@Path("queryPublicAdvisoryQuestionPage")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPublicAdvisoryQuestion(@QueryParam("Page") String page, @QueryParam("Number") String number)
			throws UnsupportedEncodingException {
		try {
			int start=Integer.parseInt(page)*Integer.parseInt(number);
			String sql="select * from question where private="+0+" ORDER BY createdate DESC LIMIT "+ start +"," + number;
			List<Question> question=DaoFactory.getInstance().getQuestion_dao().query(sql);

            if (question != null && question.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, question);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//分页查询公开问题，view
	@GET
	@Path("queryPublicAdvisoryQuestionView")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPublicAdvisoryQuestionView(@QueryParam("Page") String page, @QueryParam("Number") String number)
			throws UnsupportedEncodingException {
		try {
			int start=Integer.parseInt(page)*Integer.parseInt(number);
			String sql="select * from public_question_view  ORDER BY createdate DESC LIMIT "+ start +"," + number;
			List<PublicQuestionView> question=DaoFactory.getInstance().getPublicQuestionView_dao().query(sql);
            if (question != null && question.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, question);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	// 增加新的提问,成功返回id
	@GET
	@Path("addPublicAdvisoryQuestion")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String addPublicAdvisoryQuestion(@QueryParam("json") String json)
			throws UnsupportedEncodingException {
		try {
			if (json != null && !json.equals("")) {
				json = URLDecoder.decode(json);
				Question q = (Question) CommonJson.Json2Obj(json, Question.class);
				if (q != null) {
					q.setId(IDOperation.getClassID(Question.class.getName()));
					q.setAnswercount(0);
					q.setCreatedate(DateFormater.getTimestampByString(DateFormater.formatLongDateTime(new Date())) );
				}

				if (DaoFactory.getInstance().getQuestion_dao().save(q)) {
					return BuildResult.getResult(BuildResult.Success, q.getId());
				}

    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "提问失败");
	}
	
	//新增问题的图片
	public String addQuestionImage(String questionID,String imagePath)
			throws UnsupportedEncodingException {
		try {
			  List<Question> q=DaoFactory.getInstance().getQuestion_dao().findByProperty("id", questionID);
			  if(q.get(0).getPic()!=null&&!q.get(0).equals("")){
				  q.get(0).setPic(q.get(0).getPic()+","+imagePath);
			  }else{
                  q.get(0).setPic(imagePath);
			  }
				if (DaoFactory.getInstance().getQuestion_dao().update(q.get(0))) {
					return BuildResult.getResult(BuildResult.Success,"添加图片成功");
				}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "添加图片失败");
	}
	
	//查询所有的回复
	@GET
	@Path("queryPublicQuestionAnswer")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPublicQuestionAnswer(@QueryParam("QuestionID") String questionID)
			throws UnsupportedEncodingException {
		try {
			String sql="select * from normal_answer where questionid='"+questionID+"' ORDER BY createdate DESC";
            List<NormalAnswer> normalAnswer=DaoFactory.getInstance().getNormalAnswer_dao().query(sql);
            if (normalAnswer != null && normalAnswer.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, normalAnswer);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//新增回复
	@GET
	@Path("addPublicQuestionAnswer")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String addPublicQuestionAnswer(@QueryParam("normalAnswer") String normalAnswer)
			throws UnsupportedEncodingException {
		try {
			if(normalAnswer!=null&&!normalAnswer.equals("")){
				normalAnswer = URLDecoder.decode(normalAnswer);
				NormalAnswer answer = (NormalAnswer) CommonJson.Json2Obj(normalAnswer, NormalAnswer.class);
				if (answer != null) {
					answer.setId(IDOperation.getClassID(NormalAnswer.class.getName()));
					answer.setCreatedate(DateFormater.getTimestampByString(DateFormater.formatLongDateTime(new Date())) );
				}

				if (DaoFactory.getInstance().getNormalAnswer_dao().save(answer)) {
					return BuildResult.getResult(BuildResult.Success, answer.getId());
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "回复失败");
	}
	
	//查询用户所有的私有提问
	@GET
	@Path("queryAllPrivateAdvisoryQuestion")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryAllPrivateAdvisoryQuestion(@QueryParam("userID") String userID)
			throws UnsupportedEncodingException {
		try {
			String sql="select * from question where private="+1+" and userid='"+userID+"' ORDER BY createdate DESC";
			List<Question> question=DaoFactory.getInstance().getQuestion_dao().query(sql);

            if (question != null && question.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, question);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//分页查询用户所提的私有问题
	@GET
	@Path("queryPrivateAdvisoryQuestionPage")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPrivateAdvisoryQuestion(@QueryParam("userID") String userID,
			@QueryParam("Page") String page,
			@QueryParam("Number") String number )
			throws UnsupportedEncodingException {
		try {
			int start=Integer.parseInt(page)*Integer.parseInt(number);
			String sql="select * from question where private="+1+" and userid='"+userID+"' ORDER BY createdate DESC LIMIT "+start+","+number;
			List<Question> question=DaoFactory.getInstance().getQuestion_dao().query(sql);

            if (question != null && question.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, question);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//分页查询用户所提的私有问题,view
	@GET
	@Path("queryPrivateAdvisoryQuestionView")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPrivateAdvisoryQuestionView(@QueryParam("userID") String userID,
			@QueryParam("Page") String page,
			@QueryParam("Number") String number )
			throws UnsupportedEncodingException {
		try {
			int start=Integer.parseInt(page)*Integer.parseInt(number);
			String sql="select * from private_question_view where userid='"+userID+"' ORDER BY createdate DESC LIMIT "+start+","+number;
			List<PrivateQuestionView> question=DaoFactory.getInstance().getPrivateQuestionView_dao().query(sql);

            if (question != null && question.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success,question);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//查询私有问题的回复
	@GET
	@Path("queryPrivateQuestionAnswer")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPrivateQuestionAnswer(@QueryParam("QuestionID") String questionID)
			throws UnsupportedEncodingException {
		try {
			String sql="select * from private_answer where questionid='"+questionID+"' ORDER BY createdate ASC";
            List<PrivateAnswer> privateAnswer=DaoFactory.getInstance().getPrivateAnswer_dao().query(sql);
            
            if (privateAnswer != null && privateAnswer.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, privateAnswer);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	//查询私有问题的回复，view
	@GET
	@Path("queryPrivateQuestionAnswerView")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String queryPrivateQuestionAnswerView(@QueryParam("QuestionID") String questionID)
			throws UnsupportedEncodingException {
		try {
			String sql="select * from private_answer_view where questionid='"+questionID+"' ORDER BY createdate ASC";
            List<PrivateAnswerView> privateAnswer=DaoFactory.getInstance().getPrivateAnswerView_dao().query(sql);
            
            if (privateAnswer != null && privateAnswer.size() >= 0) {
    			return BuildResult.getListResult(BuildResult.Success, privateAnswer);
    		}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "查询失败");
	}
	
	
	//新增私有问题的回复
	@GET
	@Path("addPrivateQuestionAnswer")
	@Produces(MediaType.APPLICATION_OCTET_STREAM)
	public String addPrivateQuestionAnswer(@QueryParam("privateAnswer") String privateAnswer)
			throws UnsupportedEncodingException {
		try {
			if(privateAnswer!=null&&!privateAnswer.equals("")){
				privateAnswer = URLDecoder.decode(privateAnswer);
				PrivateAnswer answer = (PrivateAnswer) CommonJson.Json2Obj(privateAnswer, PrivateAnswer.class);
				if (answer != null) {
					answer.setId(IDOperation.getClassID(PrivateAnswer.class.getName()));
					answer.setCreatedate(DateFormater.getTimestampByString(DateFormater.formatLongDateTime(new Date())) );
				}

				if (DaoFactory.getInstance().getPrivateAnswer_dao().save(answer)) {
					return BuildResult.getResult(BuildResult.Success, answer.getId());
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "回复失败");
	}
	
	//新增回复的图片
	public String addAnswerImage(String answerID,String imagePath)
			throws UnsupportedEncodingException {
		try {
			  List<PrivateAnswer> pa=DaoFactory.getInstance().getPrivateAnswer_dao().findByProperty("id", answerID);
			  if(pa.get(0).getAnswer_pic()!=null&&!pa.get(0).equals("")){
				  pa.get(0).setAnswer_pic(pa.get(0).getAnswer_pic()+","+imagePath);
			  }else{
                  pa.get(0).setAnswer_pic(imagePath);
			  }
				if (DaoFactory.getInstance().getPrivateAnswer_dao().update(pa.get(0))) {
					return BuildResult.getResult(BuildResult.Success,"添加图片成功");
				}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return BuildResult.getResult(BuildResult.failed, "添加图片失败");
	}

}
